package com.aws.remote;

import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.s3.transfer.TransferManager;
import com.amazonaws.services.s3.transfer.Upload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.Arrays;
import java.util.Objects;
import java.util.stream.Stream;

/**
 * @description:
 * @author: libugu@cskaoyan.com
 * @date 2024/1/17 - 17:36
 */
@Component
public class RemoveDemo3 {
    String bucketName = "mylibugu";
    String localFolderPath = "C:\\Users\\libugu\\Desktop\\2027";
    String folderKeyword = "12";
    @Autowired
    AmazonS3 s3Client;

    public void test(){
        String localFolderPath = "C:\\Users\\libugu\\Desktop\\2027";

        // 设置 S3 存储桶名称和前缀
        String bucketName = "mylibugu";
        String prefix = "13";

        try {
            // 递归遍历本地文件夹并上传到 S3
            File folder = new File(localFolderPath);
            uploadFilesToS3(s3Client, folder, bucketName, prefix);

            // 关闭 S3 客户端
            s3Client.shutdown();
            System.out.println("迁移成功");
        } catch (Exception e) {
            System.out.println("迁移失败");
            throw new RuntimeException(e);
        }
    }

    private static void uploadFilesToS3(AmazonS3 s3Client, File file, String bucketName, String prefix) {
        if (file.isDirectory()) {
            // 如果是文件夹，则处理子文件夹和文件
            File[] files =  Arrays.stream(file.listFiles()).filter(file1 -> file1.getName().startsWith(prefix)).toArray(File[]::new);
            if (files != null) {
                for (File subFile : files) {
                    File[] files1 = subFile.listFiles();
                    for (File file1 : files1) {
                        if(file1.isFile()){
                            String s3Key = "user/test/"+subFile.getName()+"/"+file1.getName();
                            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, s3Key, file1);
                            s3Client.putObject(putObjectRequest);
                            System.out.println("Successfully uploaded file: " + s3Key);

                        }
                    }
                }
            }
        }
    }



}



